package algorithm.stack;

public class Calculator {
    public static void main(String[] args) {
        String s = "3+6*8/7";
        System.out.println(cal(s));
    }

    public static float cal(String s) {
        int index = 0;
        float num1 = 0;
        float num2 = 0;
        char oper = ' ';
        MyStack numStack = new MyStack(10);
        MyStack operStack = new MyStack(10);
        float result;
        while (index <= s.length() - 1) {
            //如果是字符
            if (MyStack.chType(s.charAt(index)) == 0) {
                //如果是栈空
                if (operStack.isEmpty() || MyStack.priority(s.charAt(index)) > MyStack.priority((char) operStack.peek())) {
                    operStack.push(s.charAt(index));
                }
                //看新的符号优先级小于等于上一个符号
                else if (MyStack.priority(s.charAt(index)) <= MyStack.priority((char) operStack.peek())) {
                    oper = (char) operStack.pop();
                    num1 = numStack.pop();
                    num2 = numStack.pop();
                    result = MyStack.calcu(num1, num2, oper);
                    numStack.push(result);
                    operStack.push(s.charAt(index));
                }

            }
            //如果是数字
            if (MyStack.chType(s.charAt(index)) == 1) {
                numStack.push(s.charAt(index) - 48);
            }
            index++;
        }
        char ch = ' ';
        float n1 = 0;
        float n2 = 0;
        float val;
        //将算式入栈完毕后，计算剩下的数
        while (!operStack.isEmpty()) {
            ch = (char) operStack.pop();
            n1 = numStack.pop();
            n2 = numStack.pop();
            val = MyStack.calcu(n1, n2, ch);
            numStack.push(val);
        }
        return numStack.peek();
    }
}
